<?php 
use xfyzf\api\controller\Pay_Money_Api;
use xfyzf\api\controller\WXMac_Protocol;
use xfyzf\api\controller\WXUOS_Protocol;
use xfyzf\api\controller\Examine;
use xfyzf\api\controller\QQ_Protocol;
use lib\XFDB;
function xufeiqymoneymck($row,$srow=NULL, $send = null ){
    global $DB;
	global $conf; 
    $date = date("Y-m-d H:i:s");
    // 	$time = time();
    $E_type='支付宝免ck';
    // 	$timess = time() + rand(2, 5);
    require_once SYSTEM_ROOT  . '/aop/AopClient.php';
    require_once SYSTEM_ROOT .'/aop/request/AlipayDataBillAccountlogQueryRequest.php';
    require_once SYSTEM_ROOT .'/aop/request/AlipayDataBillBalanceQueryRequest.php';	
    $aop = new AopClient ();
    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    $aop->appId = $row['alipayAppId'];//应用ID
    $aop->rsaPrivateKey = $row['appPrivateKey'];//私钥
    $aop->alipayrsaPublicKey=$row['alipayPublicKey'];//支付宝公钥
    $aop->apiVersion = '1.0';
    $aop->signType = 'RSA2';
    $aop->postCharset='UTF-8';
    $aop->format='json';
      $request = new AlipayDataBillBalanceQueryRequest ();
    $request->setBizContent("{}");
    $result = $aop->execute($request);
     $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
     $resultCode = $result->$responseNode->code;
      $result = json_decode(json_encode($result), true);
      
       unset($result['sign']);
       $result1 = $result['alipay_data_bill_balance_query_response'];  
       $money = $result1['available_amount'];  //监控余额
       if($money>=0.01)$Pay_Money =$money;else$Pay_Money = '0.00';
       $sql = "update `pay_qrlist` set `money`='{$Pay_Money}' WHERE `id`='{$row['id']}'";
       executeSQLQuery($sql , 'update');
        $money_ = $row['money'];
         $Qr_Money=0;	
         if($money_!=$Pay_Money){
        		$Qr_Money = $Pay_Money-$money_;//实时余额减去上次系统记录余额=本次收款到账金额
        }
        if($Qr_Money>0){
            $Qr_Money1 = round($Qr_Money, 2); 
            // $bool = false;
            $type=$row['type'];
            return notify($E_type,$type,$Qr_Money1,$row['id']);
    }
}
    
    
    
    
/**
 * 检查支付通知
 * @param array $row 支付信息数组
 * @param string|null $send 发送者信息（可选）
 * @return string 返回通知信息
 */
function check_money_notify($row,$send = null){
    global $conf,$date;
    if ($row['type'] == 'alipay') {
        $methodName = ($row['xf_type'] == '1') ? 'Get_pay_money' : 'Get_pay_money' . $row['xf_type'];
        $Pay_Money_Api = Pay_Money_Api::$methodName($row['type'], $row['cookie']);
    } else {
        $Pay_Money_Api = Pay_Money_Api::Get_pay_money($row['type'], $row['cookie']);
    }
    
    $E_type = ($row['type'] == 'alipay') ? '支付宝' : 'QQ钱包';
	$timess=time()+  mt_rand(30, 45);
	if($Pay_Money_Api['money']>=0.01)$Pay_Money = $Pay_Money_Api['money'];else$Pay_Money = '0.00';
	$money_ = $row['money'];
	$Qr_Money = 0;
	
	if($money_!=$Pay_Money){
		$Qr_Money = $Pay_Money-$money_;//实时余额减去上次系统记录余额=本次收款到账金额
	}
	
	if(!$Pay_Money_Api['status']){
	    if($row['type'] == 'qqpay' && $row['xf_stat'] == '1' && $row['hook_type'] == '0'){
	        if(QQPCGX($row,true)){
	            $sql = "update `pay_qrlist` set `crontime`='{$timess}' WHERE `id`='{$row['id']}'";
	            executeSQLQuery($sql,'update');
	            return '';
	        }
	    }else{
	        $sql = "update `pay_qrlist` set `status`='0',`cookie`='0',`data_data`='0',`endtime`='{$date}' WHERE `id`='{$row['id']}'";
    	    executeSQLQuery($sql,'update');
    	    $sql = "SELECT email FROM pay_user WHERE pid='{$row['pid']}' limit 1";
    	    $res =  executeSQLQuery($sql)['email'];
    	    xfqrnostatusemail($res,$E_type);
    	    return $E_type.'ID:'.$row['id'].'---已掉线---';
	    }
	    
	}
	if($Qr_Money || $Pay_Money){
	    $sql = "update `pay_qrlist` set `money`='{$Pay_Money}',`crontime`='{$timess}' WHERE `id`='{$row['id']}'";
	    executeSQLQuery($sql,'update');
	}
	return $E_type.'ID:'.$row['id'].'---余额：'.$Pay_Money.'元---';
}

function wxyun_money_notify($row){
    global $conf,$date;
    $timess=time()+  mt_rand(45, 80);
    $sebei = Examine::sebei($row['xf_type']);
    $typeDescriptions = [
        '1' => '微信个码通道(IMAC)',
        '2' => '微信收款单通道(UOS)',
        '3' => '微信个码通道(UOS)',
        '4' => '微信赞赏码通道(UOS)',
        '5' => '微信经营码通道(UOS)',
        '6' => '小微商家通道(UOS)',
        '7' => '微信收款单通道(IMAC)',
        '8' => '微信赞赏码通道(IMAC)',
        '9' => '微信经营码通道(IMAC)',
        '10' => '微信经营码通道(IMAC)'
    ];
    $E_type = $typeDescriptions[$row['xf_type']] ?? '未知通道';
    if($E_type == '未知通道'){
        $sql = "update `pay_qrlist` set `crontime`='{$timess}' WHERE `id`='{$row['id']}'";
        executeSQLQuery($sql,'update');
        return 'ID:'.$row['id'].'---状态正常---';
    }
    $WxApi = createWxApiInstance($row);
      $WXHeart = $WxApi->WXHeartBeat($row['cookie']);
    if ($WXHeart['code'] == '1'){
        $sql = "update `pay_qrlist` set `crontime`='{$timess}' WHERE `id`='{$row['id']}'";
        executeSQLQuery($sql,'update');
    }else{
        $sql = "SELECT email FROM pay_user WHERE pid='{$row['pid']}' limit 1";
	    $res =  executeSQLQuery($sql)['email'];
	    xfqrnostatusemail($res,$E_type);
	    $sql = "update `pay_qrlist` set `status`='0',`cookie`='0',`data_data`='0',`endtime`='{$date}' WHERE `id`='{$row['id']}'";
	    executeSQLQuery($sql,'update');
	    return $E_type.'ID:'.$row['id'].'---已掉线---';
    }
    return $E_type.'ID:'.$row['id'].'---状态正常---';
}

function QQPCGX($row,$send = false){
    // 获取 QQPC 的 cookie 和状态信息
   
    $json = QQ_Protocol::GET_QQPCCOOKIE($row['beizhu'], $row['xf_type']);

    // 获取用户的邮箱
    $email = executeSQLQuery("SELECT email FROM pay_user WHERE pid='{$row['pid']}' LIMIT 1")['email'];

    // 更新 cookie 时间为下一天的当前时间
    $nextDay = date('Y-m-d H:i:s', strtotime('+3 hours')); 

    // 根据返回的状态码进行相应操作
    switch ($json['code']) {
        case 2:
        case -2:
        case -1:
            // 更新数据库信息并发送邮件通知
            executeSQLQuery("UPDATE `pay_qrlist` SET `cookie` = '0', `status` ='0' WHERE `id` = '{$row['id']}'",'update');
            xfqrnostatusemail($email, 'QQ云端');
            return (!$send)?'二维码ID'.$row['id'].'未登录或状态异常:'.$json['msg'].'---':false;
        default:
            // 如果状态正常，更新数据库信息
            $Pay_Money = Pay_Money_Api::Get_pay_money($row['type'], $json['cookie']);
            if (!$Pay_Money['status']) {
                executeSQLQuery("UPDATE `pay_qrlist` SET `cookie` = '0', `status` ='0' WHERE `id` = '{$row['id']}'",'update');
                xfqrnostatusemail($email, 'QQ云端');
                return (!$send)?'二维码ID'.$row['id'].'已退出登录更新失败---':false;
            } else {
                if($Pay_Money['money']>=0.01)$Pay_Money = $Pay_Money['money'];else$Pay_Money = '0.00';
                executeSQLQuery("UPDATE `pay_qrlist` SET `cookie` = '{$json['cookie']}', `chatime` ='{$nextDay}' , `money` = '{$Pay_Money}' WHERE `id` = '{$row['id']}'",'update');
                return (!$send)?'二维码ID'.$row['id'].'CK更新成功---':true;
            }
    }
}
function xfwxpcgua($QR_row){
    $timess=time()+mt_rand(40, 80);
    $sql = "update `pay_qrlist` set `status`='1',`cookie`='1' ,`crontime`='{$timess}'WHERE `id`='{$QR_row['id']}'";
    executeSQLQuery($sql,'update');
    return true;
}
function wxpcdycron($QR_row){
    $timess=time()+mt_rand(40, 80);
    $sql = "update `pay_wechat_trumpet` set `status`='1',`cookie`='1' ,`crontime`='{$timess}'WHERE `id`='{$QR_row['id']}'";
    executeSQLQuery($sql,'update');
    return true;
}

function xfpcgua($QR_row){
    $sql = "update `pay_qrlist` set `status`='0' WHERE `id`='{$QR_row['id']}'";
    return executeSQLQuery($sql,'update');
}
function ALIQQ_money_notify($row,$send=NULL){
   if ($row['type'] == 'alipay') {
        $methodName = ($row['xf_type'] == '1') ? 'Get_pay_money' : 'Get_pay_money' . $row['xf_type'];
        $money = Pay_Money_Api::$methodName($row['type'], $row['cookie']);
    } else {
        $money = Pay_Money_Api::Get_pay_money($row['type'], $row['cookie']);
    }
    
    $timess=time()+  mt_rand(45, 80);
    $xftime1=time();
    $name = array(
        'qqpay'=>'QQ钱包',
        'alipay'=>'支付宝'
        );
    $E_type = $name[$row['type']];
    if($money['money']>=0.01)$Pay_Money = $money['money'];else$Pay_Money = '0.00';
    $sql = "update `pay_qrlist` set `money`='{$Pay_Money}',`crontime`='{$timess}' WHERE `id`='{$row['id']}'";
    executeSQLQuery($sql,'update');
    $money_ = $row['money'];
    $Qr_Money=0;
    if($money_!=$Pay_Money){
		$Qr_Money = $Pay_Money-$money_;//实时余额减去上次系统记录余额=本次收款到账金额
	}

	if($Qr_Money>0){
	    $Qr_Money1 = round($Qr_Money, 2); 
	    $qr_id = $row['id'];
	    return notify($E_type,$row['type'] , $Qr_Money1 , $qr_id);
	}
}

function QQOrder_notify($row){
    $time = time();
    $sql = "SELECT * FROM pay_user WHERE pid='{$row['pid']}' limit 1";
    $rew =  executeSQLQuery($sql);
    if($row['type']!='qqpay')return false;
    $type = 'QQ钱包';
    $Cookie=base64_decode($row['cookie']);
    $qr_id = $row['id'];
    $uin = explode("qluin=",$Cookie);
    $skey = getSubstr($Cookie,"skey=", ";");
    $p_skey = "p_skey=".getSubstr($Cookie,"p_skey=", ";").";";
    $Url = 'https://myun.tenpay.com/cgi-bin/clientv1.0/qwallet_record_list.cgi?limit=20&offset=0&s_time=2021-07-10&ref_param=&source_type=7&time_type=0&bill_type=0&uin='.$uin[1];
    $Get_Order = json_decode(get_curl($Url,0,0,$p_skey), true);
    if($Get_Order['records']){
        foreach ($Get_Order['records'] as $item){
            $money = $item['amount']/100;
            $order_time = strtotime($item['create_time']);
            // return notify($E_type,$row['type'] , $money , );
            $sql = "SELECT * FROM pay_order WHERE status='0' and pid='{$row['pid']}' and type='{$row['type']}' and price='{$money}' and outtime>'{$order_time}' and addtime<'{$item['create_time']}' and qr_id = '{$qr_id}' limit 1";
            $srow = executeSQLQuery($sql);
            if(!empty($srow)){
                if($srow['status']==0){
                     $xf_pid=$srow['pid'];
                     $xf_money=$srow['price'];
                     $url=creat_callback($srow);
                     $data=get_curl($url['notify']);
                     xfhtemail($xf_pid,$xf_money,$type,$srow['name'],$srow['trade_no']); 
                     createLog($xf_pid,'自动回调订单('.$E_type.')：'.$srow['trade_no'],http_ip());
                     exit($data);
                }
            }
        }
    }
}

function WXGM_notify($QR_row){
    // 根据不同的 xf_type 创建相应的 WxApi 实例
    $WxApi = createWxApiInstance($QR_row);
    
    // 如果创建实例失败，则返回false
    if (!$WxApi) {
        return false;
    }
    
    // 获取传入的参数
    $cookie = $QR_row['cookie'];
    $qr_id = $QR_row['id'];
    $E_type = '微信个码';
    $xftime1 = time();
    
    // 调用 WxApi 实例的 Order 方法获取订单信息
    $Order = $WxApi->Order($cookie);
    $moneygm3 = '/支付收款(.*?)元/';
    preg_match($moneygm3, $Order, $trStrmgm);
    $wxpaymoneygm3 = $trStrmgm[1];
    
    // 如果订单金额不为空，则查询相应的订单信息
    if (!empty($wxpaymoneygm3)) {
        return notify($E_type , $QR_row['type'] , $wxpaymoneygm3 , $qr_id);
    }
}

function WXskd_notify($QR_row){
     $WxApi = createWxApiInstance($QR_row);
    // 如果创建实例失败，则返回false
    if (!$WxApi) {
        return false;
    }
    $cookie = $QR_row['cookie'];
	$qr_id = $QR_row['id'];
    $E_type = '微信收款单';
    $xftime1=time();
    $Order = $WxApi->Order($cookie);
    $moneygm3 = '/收款金额¥(.*?)n付款方昵称/';
    $ordergm3 = '/收款说明(.*?)n汇总/';
    preg_match($moneygm3,$Order,$trStrmgm);
    preg_match($ordergm3,$Order,$trStrogm);
    $wxpaymoneygm3=$trStrmgm[1]; 
    $wxpayordergm3=$trStrogm[1];
    if(!empty($wxpaymoneygm3) || !empty($wxpayordergm3)){
        return notify($E_type,$QR_row['type'] , $wxpaymoneygm3 , $qr_id);
    }
}

function WXZSM_notify($QR_row){
    $WxApi = createWxApiInstance($QR_row);
    // 如果创建实例失败，则返回false
    if (!$WxApi) {
        return false;
    }
    $cookie = $QR_row['cookie'];
    $qr_id = $QR_row['id'];
    $E_type = '微信赞赏码';
    $Order = $WxApi::Order($cookie);
    $moneygm3 = '/二维码赞赏到账(.*?)元/';
    preg_match($moneygm3,$Order,$trStrmgm);
    $wxpaymoneygm3=$trStrmgm[1];
    $xftime1=time();
    if(!empty($wxpaymoneygm3)){
        return notify($E_type , $QR_row['type'] , $wxpaymoneygm3 , $qr_id);
       
    }
}

function WXJYM_notify($QR_row){
     $WxApi = createWxApiInstance($QR_row);
    // 如果创建实例失败，则返回false
    if (!$WxApi) {
        return false;
    }
	 $E_type = '微信经营码';
	 $xftime1=time();
	 $cookie = $QR_row['cookie'];
	 $qr_id = $QR_row['id'];
	 $Order = $WxApi->Order($cookie);
	 $moneygm3 = '/支付收款(.*?)元/';
	 preg_match($moneygm3,$Order,$trStrmgm);
	 $wxpaymoneygm3=$trStrmgm[1];

	 if(!empty($trStrmgm)){
	     return notify($E_type , $QR_row['type'] , $wxpaymoneygm3 , $qr_id);
	 }
}
/**
 * 微信小微商家支付通知处理
 * 
 * 此函数通过解析支付通知来自动处理和确认订单状态。根据传入的支付类型，使用不同的协议处理逻辑。
 * 它会获取支付订单，并匹配订单且未过期的记录，然后执行回调并退出脚本。
 *
 * @param array $QR_row 包含支付信息的数组，不同字段包括:
 *               - xf_type: 支付类型
 *               - cookie: 用于API请求身份验证
 *               - id: 订单ID
 * @return void 此函数没有返回值，直接调用 exit($data) 在成功处理支付回调后退出脚本，或者根据条件返回 false。
 */
function WXXWSJ_notify($QR_row){
     $WxApi = createWxApiInstance($QR_row);
    // 如果创建实例失败，则返回false
    if (!$WxApi) {
        return false;
    }
	 $E_type = '微信小微商家';
	 $xftime1=time();
	 $cookie = $QR_row['cookie'];
	 $qr_id = $QR_row['id'];
	 $Order = $WxApi::Order($cookie);
	 $moneygm3 = '/收款(.*?)元/';  
	 preg_match($moneygm3,$Order,$trStrmgm);
	 $wxpaymoneygm3=$trStrmgm[1];
	 if(!empty($wxpaymoneygm3)){
	     return notify($E_type , $QR_row['type'] , $wxpaymoneygm3 , $qr_id);
	 }
}

/**
 * 检查USDT支付状态
 * 
 * 此函数负责通过QR URL检查特定的USDT地址余额，并更新支付单据状态。
 * 该函数依赖全局变量 $conf 和 $date，以及外部调用的 get_curl 和 executeSQLQuery 函数。
 *
 * @param array $QR_row 包含QR信息的数组，包括: qr_url(支付地址), money(金额), type(类型), id(QR识别ID)
 * @return mixed 如果余额未发生变动返回查询到的余额, 有变动则进行回调并自动处理订单, 直接退出脚本
 * @global array $conf 全局配置信息
 * @global int $date 当前日期时间
 */
function check_usdt($QR_row){
    global $conf,$date;
    if($QR_row['qr_url'] == 'TMUZGvGyaZR7u1TKFXiL5psgX9KzbykxSh') return false;
    $url = "https://usdt.tokenview.io/api/usdtsearch/" . $QR_row['qr_url'];
    $result = get_curl($url);
    $json   = json_decode($result,true);
    if($json['code'] == 1 && $json['data'][0]['balance'] !== false){
        $money = $json['data'][0]['balance'];
        $money_ = $QR_row['money'];
        if($money>=0.01)$Pay_Money =$money;else$Pay_Money = '0.00';
        executeSQLQuery("update `pay_qrlist` set `money`='{$Pay_Money}' WHERE `id`='{$QR_row['id']}'","update");
        if($money_!=$Pay_Money){
        	$Qr_Money = $Pay_Money-$money_;//实时余额减去上次系统记录余额=本次收款到账金额
        }
        if($Qr_Money>0){
            $Qr_Money1 = round($Qr_Money, 2); 
             $type=$QR_row['type'];
             $E_type = 'USDT支付';
             return notify($E_type , $QR_row['type'] , $Qr_Money1 , $QR_row['id']);
             
        }else{
            return false;
        }
        
    }
}

function wxyunsid($row){
    $WxApi = createWxApiInstance($row);
    $XW=$WxApi->Xwcode($row['cookie']);
    
    if($XW['code'] == 1){
       return $XW;
    }
     return false;
}

// 根据 xf_type 创建相应的 WxApi 实例
function createWxApiInstance($QR_row) {
    $wxyunurl = XFDB::wxyunurlrow($QR_row['wxyunurl']);
    $url = ($wxyunurl && $wxyunurl['status'] == 1)?$wxyunurl['url']:'';
   
    if(Examine::sebei($QR_row['xf_type']) == 'Mac'){
        return new WXMac_Protocol($url);
    }else{
        return new WXUos_Protocol($url);
    }
}

function wxmacgrskdqrurl($QR_row,$price,$trade_no){
    $token = wxyunsid($QR_row);
    if($token['code']!=1)sysmsg($token['msg']);  
    $WxApi = createWxApiInstance($QR_row);
    $XWskdgm = $WxApi->WXID($token['sid'], $price, $trade_no, $token['account_id']);
    if($XWskdgm['code']!=1)sysmsg($XWskdgm['msg']);  
    if (!$XWskdgm['receipt_id']) sysmsg('创建失败!');
    $QR = $WxApi->WXskdqrcode($token['sid'], $token['account_id'], $XWskdgm['receipt_id']);
    if($QR['code']!=1)sysmsg($QR['msg']);  
    $base64_image_content = 'data:image/bmp;base64,' . $QR['qrcode'];
    return $base64_image_content;
      
}


function wxgmqrurl($QR_row,$money,$trade_no){
	$WxApi = createWxApiInstance($QR_row);
	$QR_row = $WxApi->WXF2FQrcode($QR_row['cookie'], $money,$trade_no );
	$QR_row = json_decode($QR_row, true)['pay_url'];
    return $QR_row;
}


function xfnotify_url($QR_row, $srow){
    switch ($srow['type']) {
        case 'alipay':
            ALIQQ_money_notify($QR_row, true);
            break;
        case 'wxpay':
            handleWeChatPaymentNotification($QR_row);
            break;
        case 'qqpay':
            QQOrder_notify($QR_row);
            break;
        case 'usdtpay':
            check_usdt($QR_row);
            break;
        default:
            // Handle other payment types if needed
            break;
    }
}
function handleWeChatPaymentNotification($QR_row) {
    if ($QR_row['hook_type'] == 2) {
        
        switch ($QR_row['xf_type']) {
            case '1':
            case '3':
                WXGM_notify($QR_row);
                break;
            case '2':
            case '7':
                WXskd_notify($QR_row);
                break;
            case '4':
            case '8':
                WXZSM_notify($QR_row);
                break;
            case '5':
            case '9':
                WXJYM_notify($QR_row);
                break;
            case '6':
            case '10':
                WXXWSJ_notify($QR_row);
                break;
            default:
                // Handle other WeChat payment types if needed
                break;
        }
    }
}
?>